package io.github.veigara.tcp.framework.protocol;

import io.github.veigara.tcp.framework.model.DeviceConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author : zhouhx
 * 协议处理器接口
 * @date : 2025/6/6 11:25
 */
public interface ProtocolHandler {
    final Logger logger = LoggerFactory.getLogger(ProtocolHandler.class);

    void handleMessage(Object message);

    void setDeviceConnection(DeviceConnection connection);

    DeviceConnection getDeviceConnection();

    default void disconnect(){
        DeviceConnection connection = getDeviceConnection();
        if (connection != null) {
            connection.disconnect();
        }
        logger.info("Disconnected from device: {}", connection.getDeviceConnectionInfo().getDeviceId());
    }

    // 使用此方法发送消息，而不是直接调用DeviceConnection
    default void sendMessage(Object message) {
        DeviceConnection connection = getDeviceConnection();
        if (connection != null && connection.isConnected()) {
            connection.sendMessage(message);
        } else {
            logger.warn("Device connection is not available, cannot send message: {}", message);
        }
    }
}
